<?php
declare(strict_types=1);

namespace Service\AddressService;

use Service\BaseService;
use App\Model\BbcModel\Address;
use Service\AuthService\IdCardAuthService;
use Service\Code\Normal;
use Service\AddressService\Volidate\AddressVolidate;
use Service\ConfigureService\ChannelConfigService;
use App\Model\BbcModel\AddressSelfdelivery;
use Service\AreaService\AreaService;
use App\Model\BbcModel\MemberInfo;

class AddressService extends BaseService
{
    
    /**
     * 新增收货地址
     * @param    array
     * @access   public
     * @return   array
     */
    public function newAddress(array $param = []):array
    {
        $res = AddressVolidate::instance()->validateCreate($param);
        if ($res['code'] != Normal::SUC) {
            return $res;
        }

        $param['city'] = empty($param['city'])?0:$param['city'];
        $param['area'] = empty($param['area'])?0:$param['area'];
        if(isset($param['idcard']) && !empty($param['idcard'])){
            $param['idcard']= strtoupper($param['idcard']);
            $idcardauth = IdCardAuthService::instance()->checkIdCard(["true_name"=>$param['true_name'],"idcard"=>$param['idcard'],'cid'=>$param['cid']]); 
            if ($idcardauth['code'] != Normal::SUC) {
                return $idcardauth;
            }
        }
        $add_data = [
            'mid'        => $param['mid'],
            'true_name'  => $param['true_name'],
            'idcard'     => $param['idcard'] ?? '',
            'mobile'     => $param['mobile'],
            'province'   => intval($param['province']),
            'city'       => intval($param['city']),
            'area'       => intval($param['area']),
            'address'    => $param['address'],
            'card_front' => $param['card_front'] ?? '',
            'card_back'  => $param['card_back'] ?? '',
            'is_default' => !empty($param['is_default']) ? 1 : 0,
            'cd'         => time(),
        ];
        $res = Address::instance()->add($add_data);
        if(!$res){
            return Normal::returnCode(Normal::FAIL,'新增失败');
        }
        //若新增的地址为默认地址
        if ($add_data['is_default'] == 1) {
            $where = [
                ['mid', '=', $param['mid']],
                ['id', '<>', $res],
                ['is_default', '=', 1],
            ];

            Address::instance()->edit($where, ['is_default' => 0]);
        }
        return Normal::returnCode(Normal::SUC,'新增成功',$res);

    }
    
    /**
     * @编辑收货地址
     * @param    array
     * @access   public
     * @return   array
     */
    public function editAddress(array $param = []):array
    {
        $res = AddressVolidate::instance()->validateCreate($param);

        if ($res['code'] != Normal::SUC) {
            return $res;
        }
        $param['city'] = empty($param['city'])?0:$param['city'];
        $param['area'] = empty($param['area'])?0:$param['area'];
        if (empty($param['id'])) {
            return Normal::returnCode(Normal::FAIL,'expect param id');
        }

        $address   = Address::instance()->info(['id' => $param['id'], 'mid' => $param['mid'], 'df' => 0]);

        if (empty($address)) {
            return Normal::returnCode(Normal::FAIL,'地址不存在');
        }

        if(isset($param['idcard']) && !empty($param['idcard'])){
            $param['idcard']= strtoupper($param['idcard']);
            $idcardauth = IdCardAuthService::instance()->checkIdCard(["true_name"=>$param['true_name'],"idcard"=>$param['idcard'],'cid'=>$param['cid']]); 
            if ($idcardauth['code'] != Normal::SUC) {
                return $idcardauth;
            }
        }
        $edit_data = [
            'mid'       => $param['mid'],
            'true_name' => $param['true_name'],
            'idcard'    => $param['idcard']??'',
            'mobile'    => $param['mobile'],
            'province'  => intval($param['province']),
            'city'      => intval($param['city']),
            'area'      => intval($param['area']),
            'address'   => $param['address'],
            'card_front'   => $param['card_front']??'',
            'card_back'   => $param['card_back']??'',
            'is_default'=> !empty($param['is_default']) ? 1 : 0,
            'md'        => time(),
        ];

        $res = Address::instance()->edit(['id' => $param['id']], $edit_data);

        if (empty($res)) {
            return Normal::returnCode(Normal::FAIL,'编辑失败');
        }

        //若编辑的地址为默认地址
        if ($edit_data['is_default'] == 1) {
            $where = [
                ['mid', '=', $param['mid']],
                ['id', '<>', $param['id']],
                ['is_default', '=', 1],
            ];

            Address::instance()->edit($where, ['is_default' => 0]);
        }
        $info=$this->addressInfo(['id'=>$param['id'],'mid'=>$param['mid'],'cid'=>$param['cid']]);
        return Normal::returnCode(Normal::SUC,'编辑成功',$info['data']);
    }
    
    /**
     * 用户地址详情
     * @param    array $param
     * @access   public
     * @return   array
     */
    public function addressInfo(array $param = []):array
    {
        if (empty($param['mid'])) {
            return Normal::returnCode(Normal::FAIL,'expect param mid');
        }

        $where = [
            'mid'       => $param['mid'],
            'df'        => 0,
            '_fields_'  => [
                'id', 'true_name', 'idcard', 'mobile', 'province', 'city',
                'area', 'address', 'is_default','md','card_front','card_back'
            ],
            '_order_'=>[
                'is_default'=>'desc',
                'id'=>'desc'
            ],
        ];

        if (!empty($param['id'])) {
            $where['id'] = $param['id'];
        }

        if (!empty($param['is_default'])) {
            $where['is_default'] = 1;
        }

        $address = Address::instance()->info($where);
        if (empty($address)) {
            return Normal::returnCode(Normal::FAIL,'地址不存在');
        }
        $show_config= ChannelConfigService::instance()->getConfig(['code' => 'show_config','cid'=>$param['cid']]);
        $show_license=0;
        if($show_config['code'] == Normal::SUC && $show_config['data']['status'] == 1){
            $value=$show_config['data']['value'];
            $show_license=$value['license']??0;
        }
        if($show_license==1){
            $default=AddressSelfdelivery::instance()->info(['cid'=>$param['cid']]);
            if(!empty($default)){
                $address['province']=$default['province'];
                $address['city']=$default['city'];
                $address['area']=$default['area'];
                $address['address']=$default['address'];
            }
        }
        $areas = AreaService::instance()->queryAreaListById([$address['province'],$address['city'],$address['area']]);
        $address['province'] = !empty($areas[$address['province']]) ? $areas[$address['province']] : [];
        $address['city']     = !empty($areas[$address['city']]) ? $areas[$address['city']] : [];
        $address['area']     = !empty($areas[$address['area']]) ? $areas[$address['area']] : [];
        $address['buyer']=MemberInfo::instance()->info(['_fields_'=>'truename,mobile,idcard,card_front,card_back','mid'=>$param['mid']]);
        return Normal::returnCode(Normal::SUC,'获取成功',$address);
    }
}
